package com.thitech.sif.interceptor;

import com.thitech.sif.AbsOutput;
import com.thitech.sif.Executor;
import com.thitech.sif.SIFReturn;
import com.thitech.sif.context.AbsContext;
import com.thitech.sif.returntype.ReturnType;
import com.thitech.sif.utils.ReflectRunner;
import com.thitech.sif.utils.StringUtils;

/**
 * 服务返回值判断
 * @author shisheng.lian
 * @date 2014-08-06
 *
 */
public class ReturnAssertInterceptor extends AbsInterceptorHandler {

	private static final String ASSERT_METHOD_NAME = "isSuccess";

	@Override
	public boolean beforeInvoke(Executor executor)
			throws Exception {
		return true;
	}

	@Override
	public void afterInvoke(Executor executor, AbsOutput output, Throwable e) throws Exception {
		AbsContext ctx = executor.getContext();
		String raCls = ctx.getReturnAssertClass();
		if (StringUtils.isNull(raCls)) {
			getLogger().warn("no return assert class define!");
		} else {
			Class<?> raClszz = Class.forName(raCls);
			Object returnType = ReflectRunner.getInstance().invokeMethod(
					raClszz.newInstance(), 
					ASSERT_METHOD_NAME, 
					new Object[] {output.getSifReturn(), executor},
					new Class<?>[] {SIFReturn.class, Executor.class});
			if (null != returnType && returnType instanceof ReturnType) {
				ReturnType rt = (ReturnType) returnType;
				output.getSifReturn().setType(rt.getType());
			}
		}
	}

}
